package rs.networx.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//import ftn.mbs2.dao.FriendRequestCategory;
import rs.networx.dao.FriendRequestDao;
//import ftn.mbs2.dao.NottificationCategory;
import rs.networx.dao.NottificationDao;
import rs.networx.dao.PersonDao;
import rs.networx.entity.FriendRequest;
import rs.networx.entity.Nottification;
import rs.networx.entity.Person;

public class RejectFriendRequestServlet extends HttpServlet {

	private static final long serialVersionUID = 8302857691194358095L;

	@EJB
	private PersonDao personDao;
	
	@EJB
	private FriendRequestDao friendRequestDao;
	
	@EJB
	private NottificationDao nottificationDao;

	private String username;
	private String password;
	private Integer intLoggedUserID;
	private Person loggedUser;
	
	private String requestFromID;
	private Integer intRequestFromID;
	private Person requestFromPerson;
	
	private String friendRequestID;
	private Integer intFriendRequestID;
	private FriendRequest friendRequest;
	
	private Integer friendRequestsCount;
	private Integer nottificationsCount;
	
	private Set<Person> loggedUsersFriendsSet;
	private List<Person> loggedUsersFriendsList;
	
	private Set<Person> requestFromPersonsFriendsSet;
	private List<Person> requestFromPersonsFriendsList;
	
	private ArrayList<Person> mutualFriends;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		System.out.println("LOADED RejectFriendRequestServlet");
		
		response.setContentType("text/html; charset=UTF-8");
		request.setCharacterEncoding(response.getCharacterEncoding());
		
		HttpSession session = request.getSession();
		loggedUser = (Person)session.getAttribute("logovaniUser");
		
		try {	
			username = loggedUser.getEmail();
			password = loggedUser.getPassword();
			intLoggedUserID = loggedUser.getId();
			System.out.println(username + "  " + password + "  " + intLoggedUserID);
			
			requestFromID = request.getParameter("personID");
			friendRequestID = request.getParameter("friendRequestID");
			System.out.println(requestFromID + "  " + friendRequestID);
		} catch (Exception e) {
			
			//e.printStackTrace();
		}
		
		try {
			intRequestFromID = Integer.parseInt(requestFromID);
			intFriendRequestID = Integer.parseInt(friendRequestID);
			System.out.println(intRequestFromID + "  " + intFriendRequestID);
		} catch (NumberFormatException e) {
			
			//e.printStackTrace();
		}
		
		// dobavljamo friend request iz baze...
		friendRequest = friendRequestDao.findById(intFriendRequestID);
		
		if(loggedUser != null){
			if(friendRequest != null){
				// postavljamo status zahteva na rejected...
				friendRequest.setStatus(3);
				friendRequestDao.merge(friendRequest);
				
				// nadjemo osobu koja je poslala friend request...
				requestFromPerson = personDao.findById(intRequestFromID);
				
				if(requestFromPerson != null){
					// trebalo bi da dodamo novu notifikaciju da je logged user odbio friend request koji je poslao requestFromPerson...
					// adding nottification to logged user...
					Nottification nottification = new Nottification();
					nottification.setOwner(loggedUser);
					nottification.setTargetID(friendRequest.getId());
					nottification.setType(1);
					nottification.setViewed(false);
					nottification.setLink("You Rejected Friend Request From: " + 
										  "<a href=\"GoToSelectedPersonProfileServlet2?personID=" + requestFromPerson.getId() + "\"" + 
										  " target=\"_blank\"" + ">" + requestFromPerson.getFirstName() + " " + requestFromPerson.getLastName() + "</a>" + ".");	
					nottificationDao.persist(nottification);
					
					// i sada bi trebalo da dodamo i notifikaciju za osobu koja je poslala zahtev da je logged user odbio friend request...
					// adding nottification to user who sent friend request...
					Nottification nottification2 = new Nottification();
					nottification2.setOwner(requestFromPerson);
					nottification2.setTargetID(friendRequest.getId());
					nottification2.setType(1);
					nottification2.setViewed(false);
					nottification2.setLink( "<a href=\"GoToSelectedPersonProfileServlet2?personID=" + loggedUser.getId() + "\"" + 
							  				" target=\"_blank\"" + ">" + loggedUser.getFirstName() + " " + loggedUser.getLastName() + "</a>" +
							  			    " Rejected Your friend Request.");	
					nottificationDao.persist(nottification2);
					
					// sada bi trebalo dodati i po notifikaciju svim prijateljima logged usera da je logged user odbio friend request...
					// koji je poslao requestFromPerson...
					loggedUsersFriendsSet = personDao.getFriends(intLoggedUserID);
					System.out.println("loggedUsersFriendsSet: " + loggedUsersFriendsSet.size());
					
					if(loggedUsersFriendsSet == null || loggedUsersFriendsSet.size() == 0){
						// znaci da nema prijatelja, pa idemo dalje...
						System.out.println("loggedUsersFriendsSet: " + loggedUsersFriendsSet.size());
						
					}else if(loggedUsersFriendsSet != null && loggedUsersFriendsSet.size() > 0){
						loggedUsersFriendsList = new ArrayList<Person>();
						
						Iterator<Person> iter = loggedUsersFriendsSet.iterator();
					    while(iter.hasNext()){
					    	loggedUsersFriendsList.add((Person)iter.next());
					    }
					    System.out.println("loggedUsersFriendsList: " + loggedUsersFriendsList.size());
					    
					    // sada treba za svakog prijatelja logged usera napravimo po notifikaciju...
						for(int i = 0; i < loggedUsersFriendsList.size(); i++){
							// adding nottification to logged users friends(koji nisu mutual friends)...
							if(loggedUsersFriendsList.get(i).getId().equals(intRequestFromID)){
								continue;
							}
							if(personDao.checkIfMutual(intLoggedUserID, intRequestFromID, loggedUsersFriendsList.get(i).getId()) == false){
								
								Nottification nottification3 = new Nottification();
								nottification3.setOwner(loggedUsersFriendsList.get(i));
								nottification3.setTargetID(friendRequest.getId());
								nottification3.setType(2);
								nottification3.setViewed(false);
								nottification3.setLink("<a href=\"GoToSelectedPersonProfileServlet2?personID=" + loggedUser.getId() + "\"" + 
													   " target=\"_blank\"" + ">" + loggedUser.getFirstName() + " " + loggedUser.getLastName() + "</a>" + 
													   " Rejected Friend Request From " + 
													   "<a href=\"GoToSelectedPersonProfileServlet2?personID=" + requestFromPerson.getId() + "\"" + 
													   " target=\"_blank\"" + ">" + requestFromPerson.getFirstName() + " " + requestFromPerson.getLastName() + "</a>" + ".");
								nottificationDao.persist(nottification3);
							}					
						}
					}
					
					// sada bi trebalo dodati i po notifikaciju svim prijateljima requestFromPerson(osobe koja je poslala zahtev)...
					// da je logged user odbio friend request koji je requestFromPerson poslao...
					requestFromPersonsFriendsSet = personDao.getFriends(intRequestFromID);
					System.out.println("selectedPersonsFriendsSet: " + requestFromPersonsFriendsSet.size());
					
					if(requestFromPersonsFriendsSet == null || requestFromPersonsFriendsSet.size() == 0){
						// znaci da nema prijatelja, pa idemo dalje...
						System.out.println("requestFromPersonsFriendsSet: " + requestFromPersonsFriendsSet.size());
						
					}else if(requestFromPersonsFriendsSet != null && requestFromPersonsFriendsSet.size() > 0){
						requestFromPersonsFriendsList = new ArrayList<Person>();
						
						Iterator<Person> iter = requestFromPersonsFriendsSet.iterator();
					    while(iter.hasNext()){
					    	requestFromPersonsFriendsList.add((Person)iter.next());
					    }
					    System.out.println("selectedPersonsFriendsList: " + requestFromPersonsFriendsList.size());
					    
					    // sada treba za svakog prijatelja requestFromPerson-a da napravimo po notifikaciju...
						for(int i = 0; i < requestFromPersonsFriendsList.size(); i++){
							// adding nottification to requestFromPersons friends(koji nisu mutual friends)...
							if(requestFromPersonsFriendsList.get(i).getId().equals(intLoggedUserID)){
								continue;
							}
							if(personDao.checkIfMutual(intRequestFromID, intLoggedUserID, requestFromPersonsFriendsList.get(i).getId()) == false){
								
								Nottification nottification4 = new Nottification();
								nottification4.setOwner(requestFromPersonsFriendsList.get(i));
								nottification4.setTargetID(friendRequest.getId());
								nottification4.setType(2);
								nottification4.setViewed(false);
								nottification4.setLink("<a href=\"GoToSelectedPersonProfileServlet2?personID=" + loggedUser.getId() + "\"" + 
										   			   " target=\"_blank\"" + ">" + loggedUser.getFirstName() + " " + loggedUser.getLastName() + "</a>" + 
										   			   " Rejected " + 
										   			   "<a href=\"GoToSelectedPersonProfileServlet2?personID=" + requestFromPerson.getId() + "\"" + 
										   			   " target=\"_blank\"" + ">" + requestFromPerson.getFirstName() + " " + requestFromPerson.getLastName() + "'s " + "</a>" + 
										   			   " Friend Request.");
								nottificationDao.persist(nottification4);
							}							
						}
					}
					
					// sada treba i za sve mutual friends da posaljemo po notifikaciju...
					mutualFriends = personDao.getAllMutualFriends(intLoggedUserID, intRequestFromID);
					if(mutualFriends != null && mutualFriends.size() > 0){
						// saljemo notifikacije...
						System.out.println("mutualFriends: " + mutualFriends.size());
						
						for(int i = 0; i < mutualFriends.size(); i++){
							// adding notifications to all mutual friends...
							Nottification nottification4 = new Nottification();
							nottification4.setOwner(mutualFriends.get(i));
							nottification4.setTargetID(friendRequest.getId());
							nottification4.setType(2);
							nottification4.setViewed(false);
							nottification4.setLink("<a href=\"GoToSelectedPersonProfileServlet2?personID=" + loggedUser.getId() + "\"" + 
									   			   " target=\"_blank\"" + ">" + loggedUser.getFirstName() + " " + loggedUser.getLastName() + "</a>" + 
									   			   " Rejected Friend Request From " + 
									   			   "<a href=\"GoToSelectedPersonProfileServlet2?personID=" + requestFromPerson.getId() + "\"" + 
									   			   " target=\"_blank\"" + ">" + requestFromPerson.getFirstName() + " " + requestFromPerson.getLastName() + "</a>" + ".");
							nottificationDao.persist(nottification4);
						}
					}else if(mutualFriends == null || mutualFriends.size() == 0){
						// ne saljemo nista...
						System.out.println("mutualFriends: " + mutualFriends.size());
					}
					
					// sada dobavljamo i notifikacije za datog ulogovanog korisnika ako ih ima...
					nottificationsCount = nottificationDao.getNottificationsCountForLoggedUser(loggedUser);
					System.out.println("nottificationsCount: " + nottificationsCount);
					
					// sada dobavljamo neodgovorene zahteve za prijateljstvo ako ih ima...
					friendRequestsCount = friendRequestDao.getfriendRequestsCountForLoggedUser(loggedUser);
					System.out.println("friendRequestsCount: " + friendRequestsCount);
					
					// i postavljamo nonviewed notifikacije na sesiju(ako ih ima)...
					session.setAttribute("nottificationsCount", nottificationsCount);
					
					// i postavljamo te zahteve neodgovorene zahteve za prijateljstvo (ako ih ima) na sesiju...
					session.setAttribute("friendRequestsCount", friendRequestsCount);
					
					response.sendRedirect("ViewFriendRequestsLoggedUserServlet");
					return;
					
				}else if(requestFromPerson != null){
					// znaci da je doslo do greske...
					response.sendRedirect("ViewFriendRequestsLoggedUserServlet");
					return;
				}
			}else if(friendRequest == null){
				// znaci da je doslo do greske...
				response.sendRedirect("ViewFriendRequestsLoggedUserServlet");
				return;
			}
		}else if(loggedUser == null){
			request.getRequestDispatcher("Welcome.jsp").forward(request, response);
			return;
		}	
	}
		public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		doGet(request, response);
	}
	
	
}
